<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工所属商户" prop="pid">
        <el-select v-model="queryParams.pid" placeholder="请选择员工所属商户" clearable>
          <el-option
            v-for="dict in dictMap"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="staffName">
        <el-input
          v-model="queryParams.staffName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:staff:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:staff:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:staff:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:staff:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="staffList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工所属商户" align="center" :formatter="nameFormatter" prop="pid" />
      <el-table-column label="员工姓名" align="center" prop="staffName" />
      <el-table-column label="员工性别" align="center" prop="staffSex" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.staffSex"/>
        </template>
      </el-table-column>
      <el-table-column label="员工照片" align="center" prop="staffPic" >
        <template slot-scope="scope">
          <el-image :src="scope.row.staffPic" style="width: 50px; height: 50px;"/>
        </template>
      </el-table-column>
      <el-table-column label="员工评分" align="center" prop="staffStars" />
      <el-table-column label="员工单位服务时长" align="center" prop="serveUnitTime" />
      <el-table-column label="单位可服务人数" align="center" prop="serveUnitSupportNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['console:staff:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:staff:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSchedule(scope.row)"
            v-hasPermi="['console:staff:edit']"
          >排班</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户员工管理对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工所属商户" prop="pid">
          <el-select v-model="form.pid" placeholder="请选择员工所属商户" clearable>
            <el-option
              v-for="dict in dictMap"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              @keyup.enter.native="handleQuery"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名" prop="staffName">
          <el-input v-model="form.staffName" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="员工性别" prop="staffSex">
          <el-select v-model="form.staffSex" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工照片" prop="staffPic">
          <el-input v-model="form.staffPic" type="text" placeholder="请上传员工照片" disabled/>
          <ImageEdit @changeImage="changeImage" :value="form.staffPic" :limit="1"></ImageEdit>
        </el-form-item>
        <el-form-item label="服务简介" prop="staffServiceDetailText">
          <el-input v-model="form.staffServiceDetailText" placeholder="请输入服务简介" />
        </el-form-item>
        <el-form-item label="服务海报" prop="staffServiceDetailPic">
          <el-input v-model="form.staffServiceDetailPic" type="text" placeholder="请上传服务海报" disabled/>
          <ImageEdit @changeImage="changeServicePic" :value="form.staffServiceDetailPic" :limit="1"></ImageEdit>
        </el-form-item>
        <el-form-item label="员工单位服务时长" prop="serveUnitTime">
          <el-input v-model="form.serveUnitTime" placeholder="请输入员工单位服务时长" />
        </el-form-item>
        <el-form-item label="单位可服务人数" prop="serveUnitSupportNum">
          <el-input v-model="form.serveUnitSupportNum" placeholder="请输入单位可服务人数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加排班 -->
    <el-dialog  :close-on-click-modal="false" title="添加员工排班" :visible.sync="openSchedule" width="600px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px">
        <el-form-item label="服务场所" prop="buildingId">
          <el-select v-model="form2.buildingId" placeholder="请选择服务场所" clearable>
            <el-option
              v-for="dict in buildMap"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务日期" prop="serveDay">
          <el-date-picker
            v-model="form2.serveStartDay"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          -
          <el-date-picker
            v-model="form2.serveEndDay"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务时间" prop="workTime">
          <el-time-select
            placeholder="起始时间"
            v-model="form2.workStartTime"
            :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '23:59'
            }">
          </el-time-select>
          -
          <el-time-select
            placeholder="结束时间"
            v-model="form2.workEndTime"
            :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '23:59',
              minTime: form2.workStartTime
            }">
          </el-time-select>
        </el-form-item>
        <el-form-item label="休息时间" prop="sleepTime">
          <el-time-select
            placeholder="起始时间"
            v-model="form2.sleepStartTime"
            :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '23:59'
            }">
          </el-time-select>
          -
          <el-time-select
            placeholder="结束时间"
            v-model="form2.sleepEndTime"
            :picker-options="{
              start: '00:00',
              step: '00:01',
              end: '23:59',
              minTime: form2.sleepStartTime
            }">
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSchedule">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStaff, getStaff, delStaff, addStaff, updateStaff, addSchedule } from "@/api/console/staff";
import { getDictMap } from "@/api/console/info";
import ImageEdit from "@/components/ImageEdit/Index";
import { parseTime } from '@/utils/ruoyi'

export default {
  name: "Staff",
  dicts: ['sys_user_sex'],
  components: { ImageEdit },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商户员工管理表格数据
      staffList: [],
      // 员工所属商户
      dictMap: [],
      buildMap: [],
      names: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSchedule: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pid: null,
        staffName: null,
        staffSex: null,
        staffPic: null,
        staffServiceDetailText: null,
        staffServiceDetailPic: null,
        staffStars: null,
        serveUnitTime: null,
        serveUnitSupportNum: null,
      },
      // 表单参数
      form: {},
      form2: {},
      // 表单校验
      rules: {
        pid: [
          { required: true, message: "员工所属商户不能为空", trigger: "blur" }
        ],
        staffName: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" }
        ],
      },
      rules2: {}
    };
  },
  created() {
    this.getDictMap();
    this.getList();
  },
  methods: {
    changeImage($event) {
      this.form.staffPic = $event;
    },
    changeServicePic($event) {
      this.form.staffServiceDetailPic = $event;
    },
    /** 查询商户员工管理列表 */
    getList() {
      this.loading = true;
      listStaff(this.queryParams).then(response => {
        this.staffList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSchedule = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pid: null,
        staffName: null,
        staffSex: null,
        staffPic: null,
        staffServiceDetailText: null,
        staffServiceDetailPic: null,
        staffStars: null,
        serveUnitTime: null,
        serveUnitSupportNum: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 员工所属商户 */
    getDictMap() {
      getDictMap({}).then(response => {
        this.dictMap = [];
        const dictMap = (response.data || {}).supplierMap || {};
        for (const value in dictMap) {
          this.dictMap.push({
            value: value,
            label: dictMap[value]
          });
        }

        this.buildMap = [];
        const buildMap = (response.data || {}).buildingMapWhithIdKey || {};
        for (const value in buildMap) {
          this.buildMap.push({
            value: value,
            label: buildMap[value]
          });
        }
      });
    },
    nameFormatter(row) {
      const pid = row.pid;
      for (const dict of this.dictMap) {
        if (dict.value == pid) {
          return dict.label;
        }
      }
      return pid;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.staffName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商户员工管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStaff(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商户员工管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStaff(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStaff(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.staffName || this.names
      this.$modal.confirm('是否确认删除员工名称为"' + names + '"的数据项？').then(function() {
        return delStaff(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('console/staff/export', {
        ...this.queryParams
      }, `staff_${new Date().getTime()}.xlsx`)
    },
    /** 排班按钮操作 */
    handleSchedule(row) {
      this.form2 = {};
      this.form2.serveUnitSupportNum = row.serveUnitSupportNum;
      this.form2.serveUnitTime = row.serveUnitTime;
      this.form2.id = row.id;
      this.form2.pid = row.pid;
      this.openSchedule = true;
    },
    submitSchedule() {
      this.form2.serveDays = [];
      let currentDay = this.form2.serveStartDay;
      const endDay = this.form2.serveEndDay;
      while(endDay.getTime() >= currentDay.getTime()) {
        this.form2.serveDays.push(parseTime(currentDay, "{y}-{m}-{d}"));
        currentDay = new Date(currentDay.getTime() + 86400000);
      }

      this.$refs["form2"].validate(valid => {
        if (valid) {
          addSchedule(this.form2).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.openSchedule = false;
          });
        }
      });
    }
  }
};
</script>
